package com.xinlong.shop.framework.service.impl;


import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.core.entity.SysRole;
import com.xinlong.shop.framework.core.entity.SysAdmin;
import com.xinlong.shop.framework.core.mapper.MemberMapper;
import com.xinlong.shop.framework.core.model.LoginAdmin;
import com.xinlong.shop.framework.core.model.LoginBuyer;
import com.xinlong.shop.framework.service.ISysRoleService;
import com.xinlong.shop.framework.service.ISysAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @Author Sylow
 * @Date 2022/5/27
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    //@Autowired
    private final ISysAdminService sysAdminService;

    private final ISysRoleService sysRoleService;

    private final MemberMapper memberMapper;



    public UserDetailsServiceImpl(ISysAdminService sysAdminService, ISysRoleService sysRoleService, MemberMapper memberMapper) {
        this.sysAdminService = sysAdminService;
        this.sysRoleService = sysRoleService;
        this.memberMapper = memberMapper;
    }

    /**
     * 主要是通过token得到username后，判断权限用
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysAdmin sysAdmin = sysAdminService.findByUserName(username);
        if (sysAdmin != null) {
            // 查找用户的权限
            List<SysRole> Roles =sysRoleService.findRolesByAdminId(sysAdmin.getId());
            return new LoginAdmin(sysAdmin, Roles);
        }

        // 寻找买家会员 username就是会员编号 memberNo
        Member member = this.memberMapper.selectByMemberNo(username);
        if (member != null) {
            return new LoginBuyer(member);
        }
        throw new UsernameNotFoundException("不存在该用户");
    }

}
